package middleware

import (
	"strconv"

	"core/enum/response"
	"core/enum/session"
	modelSession "core/model/session"
	errorSvc "core/service/error"
	iResponse "gateway/contract/response"

	"github.com/gin-gonic/gin"
)

type TokenMiddleware struct {
	ResponseSvc iResponse.IResponse `inject:""`
}

func (t TokenMiddleware) Middleware() interface{} {
	return func(c *gin.Context) {
		// 解析token
		u, err := strconv.ParseUint(c.GetHeader("id"), 10, 64) // 以10进制解析为uint64
		if err != nil {
			t.ResponseSvc.Regular(c, nil, errorSvc.NewError(response.TokenInvalid, err))
			c.Abort()
		}

		id := uint(u)
		name := c.GetHeader("name")
		account := modelSession.Account{
			ID:          id,
			AccountName: name,
		}

		c.Set(string(session.SessionAccount), account)
		c.Next()
	}
}
